<template>
  <div>
    <template v-if="id">
      <el-table :data="position"  v-loading="loading" size="mini"
                :header-cell-style=" {fontWeight:'bold',background:'#f8f8f9',color: '#515a6e',height:'40px'}" border>

        <!-- 房屋信息列 -->
        <el-table-column align="center" label="房屋信息" min-width="300">
          <template slot-scope="scope">
            <!-- 非编辑状态显示房屋信息 -->
            <template v-if="!scope.row.edit">
              {{ scope.row.leaseCertificateNumberNew ? `${scope.row.leaseCertificateNumberNew}_${scope.row.areaName}_${scope.row.streetName}` : '-' }}
            </template>

            <!-- 编辑状态显示操作按钮 -->
            <template v-else>
              <el-button type="primary" size="mini" @click="openLesseeDialog(scope.row)"> 选择房屋 </el-button>
            </template>
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作" width="320" align="center">
          <template slot-scope="scope">
            <template v-if="scope.row.status !== 0">
              <template v-if="!scope.row.edit">
                <el-button v-if="showAdd" icon="el-icon-edit" type="primary"
                    size="mini" @click="handlerEdit(scope.row)" :disabled="isDisabled"> 编辑</el-button>
                <el-button v-if="showAdd && scope.row.tenantSerialNumber>2"
                    icon="el-icon-delete" type="danger" size="mini"
                    @click="handlerDeletePosition(scope.row.id)" :disabled="isDisabled"> 删除</el-button>
              </template>
              <template v-else>
                <el-button icon="el-icon-check" type="primary"
                    size="mini" @click="handlerPositionSave(scope.row)">保存</el-button>
                <el-button icon="el-icon-close" type="danger"
                    size="mini" @click="cancelEdit(scope.row)" style="margin-left: 10px"> 取消</el-button>
              </template>
            </template>
            <template v-else>
              非正式数据（未上报或审核中）
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-row v-if="showAdd" style="margin: 10px 0;width: 100%;display: flex;justify-content: center">
        <el-button @click="addRow" type="primary" icon="el-icon-plus" circle></el-button>
      </el-row>
    </template>
    <el-result v-else icon="warning" title="提示" subTitle="请先保存基本信息再操作房屋"></el-result>

    <!-- 房屋选择弹窗 -->
    <el-dialog title="选择承房屋" :visible.sync="dialogVisible" width="50%">
      <el-input
          v-model="listPram.houseKeyword"
          placeholder="请输入租赁证编号、地址关键词"
          @keyup.enter="handleSearch"
          clearable>
        <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
      </el-input>

      <el-table
          :data="filteredTableData"
          border
          style="width: 100%; margin-top: 20px">
        <el-table-column align="center" prop="leaseCertificateNumberNew" label="租赁证编号" width="100px"></el-table-column>
        <el-table-column align="center" prop="addressValue" label="地址"></el-table-column>
        <el-table-column align="center" label="操作" width="80">
          <template slot-scope="scope">
            <el-button  type="text" @click="selectLessee(scope.row)">选择 </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>

import {addTenantRelationshipFwInfo, deleteRow} from "@/api/lessee";
import {getTenantRelationshipByTenantIdCard, list} from "@/api/house";

export default {
  name: 'house',
  props: ['id', 'isDisabled', 'uniqueId','tenantIdCard'],
  data() {
    return {
      position: [],
      loading: false,
      showAdd: true,
      originalData: {}, // 用于保存编辑前的原始数据

      // 房屋选择相关
      dialogVisible: false,
      currentRow: null,
      filteredTableData: [],
      tableLoading: false,
      listPram: {
        page: 1,
        limit: 10,
        houseKeyword: '',
      },
    }
  },
  watch: {
    id: {
      immediate: true,
      handler(val) {
        if (val) {
          this.getPositionList();
        }
      }
    }
  },
  methods: {
    // 新增行
    addRow() {
      this.position.push({
        // id: 'new_position',
        id: this.id,
        type: 1,
        edit: true,
      });
      this.showAdd = false;
    },

    // 进入编辑状态
    handlerEdit(row) {
      // 保存原始数据以便取消编辑时恢复
      this.originalData = {
        ...row,
        leaseCertificateNumberNew: row.leaseCertificateNumberNew,
        areaName: row.areaName,
        streetName: row.streetName
      };

      this.$set(row, 'edit', true);
      this.$set(row, 'type', 2);
      this.showAdd = false;
    },

    // 取消编辑
    cancelEdit(row) {
      // 恢复原始数据
      Object.assign(row, this.originalData);
      this.$set(row, 'edit', false);
      this.showAdd = true;
    },

    // 打开选择房屋弹窗
    openLesseeDialog(row) {
      this.currentRow = row;
      this.dialogVisible = true;
      this.listPram.houseKeyword = '';
      this.filteredTableData = [];
    },

    // 搜索房屋
    handleSearch() {
      if (!this.listPram.houseKeyword.trim()) {
        this.$message.warning('请输入搜索关键词');
        return;
      }

      this.tableLoading = true;
      list(this.listPram).then(res => {
        this.filteredTableData = res.records;
        if (this.filteredTableData.length === 0) {
          this.$message.info('未找到匹配结果');
        }
      }).finally(() => {
        this.tableLoading = false;
      });
    },

    // 选择房屋
    selectLessee(row) {
      this.$set(this.currentRow, 'leaseCertificateNumberNew', row.leaseCertificateNumberNew);
      this.$set(this.currentRow, 'uniqueId', row.idValue);
      // this.$set(this.currentRow, 'uniqueId', this.uniqueId);
      this.dialogVisible = false;
      this.$message.success('房屋选择成功');
    },

    // 获取房屋列表
    getPositionList() {
      this.loading = true;
      getTenantRelationshipByTenantIdCard({tenantIdCard: this.tenantIdCard}).then(res => {
        this.position = res.map(item => ({
          ...item,
          edit: false // 初始化时设置edit为false
        }));
      }).finally(() => {
        this.loading = false;
      });
    },

    // 删除房屋
    handlerDeletePosition(id) {
      this.$confirm('确认删除当前数据').then(() => {
        this.loading = true;
        deleteRow(id).then(() => {
          this.$message.success('删除成功');
          this.getPositionList();
        }).finally(() => {
          this.loading = false;
        });
      });
    },

    // 保存房屋信息
    handlerPositionSave(row) {
      this.loading = true;
      // if (row.id === 'new_position') {
      //   delete row.id;
      // }
      console.log(444)
      console.log(row)

      addTenantRelationshipFwInfo(row).then(() => {
        this.$message.success('保存成功!');
        this.$set(row, 'edit', false);
        this.showAdd = true;
        this.getPositionList();
      }).finally(() => {
        this.loading = false;
      });
    },
  }
}
</script>
